package com.tyk.bookstore.front.order.manager;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.tyk.bookstore.front.common.core.jackson.util.JsonUtil;
import com.tyk.bookstore.front.order.model.vo.OrderCreateVo;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author tyk
 * @description OrderRedisManager
 */
@Component
@RequiredArgsConstructor
@SuppressWarnings("unchecked")
public class OrderRedisManager {

    private final RedisTemplate redisTemplate;
    private static final String ORDER_CREATE_VO_PREFIX = "order:create:";
    private static final Long ORDER_CREATE_VO_EXPIRE_TIME = 2L;
    private static final TimeUnit ORDER_CREATE_VO_EXPIRE_TIME_UNIT = TimeUnit.HOURS;
    private static final ObjectMapper PARSE = new ObjectMapper();


    /**
     * 获取订单待支付过期时间
     * 单位：秒
     */
    public static Long getOrderCreateVoExpireTime() {
        return ORDER_CREATE_VO_EXPIRE_TIME_UNIT.toSeconds(ORDER_CREATE_VO_EXPIRE_TIME);
    }


    /**
     * 缓存订单创建对象
     */
    public void cacheOrderCreateVo(Long memberId, OrderCreateVo orderCreateVo) {
        String json = JsonUtil.stringify(orderCreateVo);
        redisTemplate.opsForValue().set(
                getOrderCreateVoKey(memberId),
                json,
                ORDER_CREATE_VO_EXPIRE_TIME,
                ORDER_CREATE_VO_EXPIRE_TIME_UNIT
        );
    }

    /**
     * 获取缓存的订单创建对象
     */
    public OrderCreateVo getOrderCreateVo(Long memberId) {
        try {
            String json = (String) redisTemplate.opsForValue().get(getOrderCreateVoKey(memberId));
            return PARSE.readValue(json, OrderCreateVo.class);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 删除缓存的订单创建对象
     */
    public void deleteOrderCreateVo(Long memberId) {
        redisTemplate.delete(getOrderCreateVoKey(memberId));
    }


    /**
     * 获取缓存订单创建对象的key
     */
    private String getOrderCreateVoKey(Long memberId) {
        return ORDER_CREATE_VO_PREFIX + memberId;
    }


}
